/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.foxline.clinicplus.service;

import br.com.foxline.clinicplus.entity.Address;
import br.com.foxline.clinicplus.entity.Customer;
import br.com.foxline.clinicplus.enums.Gender;
import br.com.foxline.clinicplus.util.Caracter;
import br.com.foxline.clinicplus.util.Msg;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.Query;

/**
 *
 * @author roniere
 */
@Stateless
public class CustomerService extends GenericService<Customer> {

    public CustomerService() {
        super(Customer.class);
    }

    @Override
    public void save(Customer customer) {

        customer.setPhone(Caracter.removecaracter(customer.getPhone()));
        customer.setCellular(Caracter.removecaracter(customer.getCellular()));
        customer.setAtivo(true);
        if (customer.getCpf() != null && !customer.getCpf().trim().isEmpty()) {
            if (existCustomer(customer) == null) {

                try {
                    super.save(customer);
                    Msg.messagemInfo("Paciente cadastrado com sucesso");
                } catch (Exception e) {
                    Msg.messagemInfo("Erro ao salvar !");
                    return;
                }
            } else {
                try {
                    Msg.messagemError("Erro: CPF existente !");
                } catch (Exception e) {
                    return;
                }
            }
        } else {
            super.save(customer);
            Msg.messagemInfo("Paciente cadastrado com sucesso");
        }

    }

    public List<Customer> autocomplete(String query) {
        String sql = "select c from Customer c where lower(c.name) like lower(:name) and c.ativo = true";
        Query querymanager = getEntityManager().createQuery(sql);
        querymanager.setParameter("name", "%" + query + "%");
        return querymanager.getResultList();
    }

    public void saveCustomer(Customer customer) {
        try {
            customer.setPhone(Caracter.removecaracter(customer.getPhone()));
            customer.setCellular(Caracter.removecaracter(customer.getCellular()));
            customer.setCpf(Caracter.removecaracter(customer.getCpf()));
            update(customer);
            Msg.messagemInfo("Cliente Cadastrado com Sucesso ");
        } catch (Exception erro) {
            erro.printStackTrace();
        }

    }

    public void updateCustomer(Customer customer) {
        try {
            customer.setPhone(Caracter.removecaracter(customer.getPhone()));
            customer.setCellular(Caracter.removecaracter(customer.getCellular()));
            customer.setCpf(Caracter.removecaracter(customer.getCpf()));
            update(customer);
            Msg.messagemInfo("Cliente Atualizado com Sucesso ");
        } catch (Exception erro) {
            erro.printStackTrace();
        }

    }

    public Customer existCustomer(Customer td) {
        if (td != null && (td.getCpf() == null || td.getCpf().isEmpty())) {
            return null;
        }
        Customer customer = null;
        String sql = "Select c from Customer c where lower(c.cpf) like lower(:doc) and c.ativo = true";
        
        if(td.getId() != null){
            sql += " and c.id != :id";
        }
        
        Query query = getEntityManager().createQuery(sql);
        query.setParameter("doc", td.getCpf());
        
        if(td.getId() != null){
            query.setParameter("id", td.getId());
        }
        try {
            customer = (Customer) query.getResultList().get(0);
        } catch (NoResultException erro) {
            return null;
        } catch (NonUniqueResultException nre) {
            return null;
        } catch (Exception e) {
            return null;
        }

        return customer;
    }

    public List<Customer> findCustomer(Customer customer) {
        List<Customer> customers = new ArrayList<Customer>();

        String sql = "SELECT c FROM Customer c WHERE ";

        if ((customer.getName() != null) && (!"".equals(customer.getName()))) {
            sql += " lower(c.name) like lower(:name) and  ";
        }

        if ((customer.getCpf() != null) && (!"".equals(customer.getCpf()))) {
            sql += " lower(c.cpf) like lower(:cpf) and  ";
        }

        sql += " c.ativo = true and 1=1 ORDER BY c.name ASC";

        Query query = getEntityManager().createQuery(sql);

        if ((customer.getName() != null) && (!"".equals(customer.getName()))) {
            query.setParameter("name", "" + customer.getName().replaceAll("\\s+", "%") + "%");
        }
        if ((customer.getCpf() != null) && (!"".equals(customer.getCpf()))) {
            query.setParameter("cpf", "%" + customer.getCpf() + "%");
        }

        customers = query.getResultList();
        return customers;
    }

    public List<Address> findAddresses(Customer c) {
        String sql = "SELECT a FROM Customer c JOIN c.addresses a WHERE c.id = :id";
        Query query = getEntityManager().createQuery(sql);
        query.setParameter("id", c.getId());
        return (List<Address>) query.getResultList();
    }
    
    public Long countGenderCustomer(Gender gender){
        String sql = "SELECT COUNT(c) FROM Customer c WHERE c.gender = :gender and c.ativo = true";
        Query query = getEntityManager().createQuery(sql);
        query.setParameter("gender", gender);
        return (Long) query.getResultList().get(0);
    }
    
    public Long countCustomer() {
        String sql = "select count(c) from Customer c where c.ativo = true";

        Query query = getEntityManager().createQuery(sql);

        return (Long) query.getSingleResult();

    }
    
    public List<Customer> aniversariantes(Date data, Date datafinal) {
        SimpleDateFormat sdfdia = new SimpleDateFormat("dd");
        SimpleDateFormat sdfmes = new SimpleDateFormat("MM");
        
        String sql = "select c.id from Customer c where c.ativo = true"
                + " and EXTRACT(MONTH FROM c.dateBirth) = '"+sdfmes.format(data)+"'"
                + " and EXTRACT(DAY FROM c.dateBirth) between '" +sdfdia.format(data)+"' and '"+sdfdia.format(datafinal)+"'"
                + " ORDER BY EXTRACT(DAY FROM c.dateBirth) ASC";
        
        Query query = getEntityManager().createNativeQuery(sql);
        List<Long> ids =  new ArrayList<Long>();
        ids = query.getResultList();
        
        List<Customer> list = new ArrayList<Customer>();
        
        for (Long l : ids) {
            list.add(find(l));
        }
        
        System.err.println(sql);
        return list;
    }
}
